﻿using FireStarter.Base;
using FireStarter.Base.BusinessObjectMerger;
using Firestarter.DB.Schema.BO;

namespace Firestarter.DB.Schema.Logic
{
    public class DBMergeDBForeignKey : DBMergeBO<DBForeignKey>
    {
        protected override void CopyRelationships(DBForeignKey fromPK, DBForeignKey toPK)
        {
            //We have to deal with the case of merging a DBPrimaryKey's RelatedTable relationship.
            // The merging of this relationship is not standard since we need to find the 
            // RelatedTable from the toDatabase and and link the toPk.RelatedTable to it.
            //The Related table must be created first if required so that the related columns can be added to it
            // if required.
            if (fromPK == null) return;

            if (fromPK.RelatedTable != null && toPK.RelatedTable == null) {
                var foundRelatedTable = FindToRelatedTable(fromPK, toPK);
                toPK.RelatedTable = foundRelatedTable ?? CreateTable((DBTable)toPK.ParentTable, (DBTable)fromPK.RelatedTable);
            }

            base.CopyRelationships(fromPK, toPK);
        }

        private DBTable CreateTable(DBTable toParentTable, DBTable relatedFromTable)
        {
            if (toParentTable == null || toParentTable.Database == null) return null;
            DBMergeDBTable mergeTable = (DBMergeDBTable)MergeableBORegistry.Instance.Resolve<DBTable>();
            var createdTable = mergeTable.MergeTablesColumnsOnly(relatedFromTable, null);
            toParentTable.Database.Tables.Add(createdTable);
           // createdTable.Database = toParentTable.Database;

/*            var createdTable = toParentTable.Database.Tables.CreateBusinessObject();
            createdTable.TableName = relatedFromTable.TableName;
            createdTable.PendingChangeType = ChangeType.Add;*/
            return createdTable;
        }
        private DBTable FindToRelatedTable(DBForeignKey fromBO, DBForeignKey toBO)
        {
            if (toBO.ParentTable == null || toBO.ParentTable.Database == null) return null;
            return toBO.ParentTable.Database.Tables.Find(table => table.TableName == fromBO.RelatedTableName);
        }
    }
}